import { saveBaseCargosApi } from "./api";
import { useTzRouter } from "@/vhooks/useTzRouter";
import Taro from "@tarojs/taro";
import { getDicMap, regCommonChar } from "@/utils";

const dicMap = getDicMap();

// 包装单位的数据对象
const packUnitMapObj = {
  packTypeList: {
    title: "包装单位",
    label: "件数",
    dicMap: dicMap["packTypeList"],
  },
  customsVolList: {
    title: "体积单位",
    label: "体积",
    dicMap: dicMap["customsVolList"],
  },
  customsWgtList: {
    title: "毛重单位",
    label: "毛重",
    dicMap: dicMap["customsWgtList"],
  },
};

/**
 * 通过 code 取出 packUnitMapObj 中对应的数据
 * @param {*} code
 */
export const fetchPackUnitData = (code) => {
  let dicName = "";
  if (code === "1") {
    // 包装货物 - 包装单位
    dicName = "packTypeList";
  } else if (["2", "3", "4"].includes(code)) {
    // 液态气体、气体、液体 - 体积单位
    dicName = "customsVolList";
  } else if (["5", "6", "7"].includes(code)) {
    // 精细颗粒、中型颗粒、大颗粒 - 毛重单位
    dicName = "customsWgtList";
  }
  return (
    packUnitMapObj[dicName] || {
      title: "包装单位",
      label: "件数",
      dicMap: [{ code: "", nameCn: "--请选择--", nameLabel: "--请选择--" }],
    }
  );
};

export const useGoodsForms = ({ state, dicMap, isEmpty, wrapText }) => {
  const { navigateTo } = useTzRouter();

  // 隐藏许可证信息
  const hidePermitList = (item) => {
    return item.permitsList && !item.permitsList.length && state.formsDisabled;
  };

  const appendGoods = () => {
    // 增加对应货物数据的包装种类单位字典
    const goodsLength = state.goodsForms.length;
    state.packUnitObjList[goodsLength] = fetchPackUnitData();
    console.log(state.packUnitObjList, 666);

    state.goodsForms.push({});
    // REVIEW: 这里用 nextTick 无效
    setTimeout(() => {
      Taro.pageScrollTo({
        selector: "#goodsform-" + goodsLength,
      });
    }, 500);
  };

  const deleteGoods = (goodsIndex) => {
    Taro.showModal({
      content: "确定删除该条记录吗？",
      confirmText: "确定",
      cancelText: "取消",
    }).then((res) => {
      if (res.cancel) return;
      state.goodsForms.splice(goodsIndex, 1);
    });
  };

  // 保存货物
  const saveGoods = (data) => {
    if (isEmpty(data.cargoCode)) {
      $TzNotify.danger("请输入产品编号");
      return;
    }
    if (isEmpty(data.cargoDesc)) {
      $TzNotify.danger("请输入货物说明");
      return;
    }
    console.log(data);
    saveBaseCargosApi({ ...data })
      .then(() => {
        $TzNotify.success("保存成功");
      })
      .catch((err) => {
        $TzNotify.danger(err.data.msg || "保存失败");
      });
  };

  // 包装单位

  // 初始化每个货物数据对应的包装种类单位字典
  if (!state.packUnitObjList || !state.packUnitObjList.length) {
    state.packUnitObjList = [fetchPackUnitData()];
  }

  const handlePackTypeChange = (e, rangeItem, goodsIndex) => {
    const code = rangeItem.code;
    if (!code) {
      // 种类选择空，清空包装单位的数据
      state.goodsForms[goodsIndex].packUnit = "";
      state.packUnitObjList[goodsIndex] = fetchPackUnitData();
      return;
    }
    state.packUnitObjList[goodsIndex] = fetchPackUnitData(code);
    // 清空单位选择框
    state.goodsForms[goodsIndex].packUnit = "";
  };

  return (
    <tz-view class="form-block">
      <tz-view class="goods-handle-area">
        <tz-text class="form-block-title">货物信息</tz-text>
        {!state.formsDisabled && (
          <tz-view class="goods-handle-btn">
            <tz-button type="primary" plain onClick={appendGoods}>
              添加货物
            </tz-button>
            <tz-button
              type="primary"
              plain
              onClick={() =>
                navigateTo({
                  path: "/pages/subHK/ccrn/transport/index",
                  query: {
                    transhipmentInfo: state.transhipmentInfo
                      ? JSON.stringify(state.transhipmentInfo)
                      : undefined,
                  },
                })
              }
            >
              {state.transhipmentInfo ? "编辑转运" : "添加转运"}
            </tz-button>
          </tz-view>
        )}
      </tz-view>
      {state.goodsForms.map((item, index) => (
        <tz-form class="goods-form" id={"goodsform-" + index}>
          <tz-cell title="序号" border>
            <tz-text class="no">{index + 1}</tz-text>
            {!state.formsDisabled && state.goodsForms.length > 1 && (
              <tz-icon
                onClick={() => deleteGoods(index)}
                class="tz-input-icon"
                name="trash"
              ></tz-icon>
            )}
          </tz-cell>
          <tz-cell title="产品编号" border>
            {wrapText(
              <tz-input
                disabled={state.formsDisabled}
                v-model={item.cargoCode}
                type="text"
                placeholder={state.formsDisabled ? "" : "请输入产品编号"}
                clearable
                maxlength="50"
                rules={(val) => regCommonChar(val)}
              />,
              item.cargoCode
            )}

            {!state.formsDisabled && (
              <>
                <tz-icon
                  class="tz-input-icon first-icon"
                  onClick={() => {
                    navigateTo({
                      path: "/pages/subHK/ccrn/consigneer/index",
                      query: {
                        type: "cargoCode",
                        index: index,
                      },
                    });
                  }}
                  name="search"
                ></tz-icon>
                <tz-icon
                  class="tz-input-icon"
                  name="save"
                  onClick={() => {
                    saveGoods(item);
                  }}
                ></tz-icon>
              </>
            )}
          </tz-cell>
          <tz-cell title="种类" border required>
            <tz-picker
              disabled={state.formsDisabled}
              v-model={item.packType}
              mode="selector"
              range={dicMap.definiteTypeList}
              rangeKey="nameCn"
              valueKey="code"
              onChange={(e, rangeItem) => {
                handlePackTypeChange(e, rangeItem, index);
              }}
            ></tz-picker>
          </tz-cell>
          <tz-cell title="货物说明" border required>
            {wrapText(
              <tz-input
                disabled={state.formsDisabled}
                v-model={item.cargoDesc}
                type="text"
                placeholder="请输入货物说明"
                clearable
                maxlength="256"
              />,
              item.cargoDesc
            )}
          </tz-cell>
          <tz-cell title={state.packUnitObjList[index].label} border required>
            <tz-input
              disabled={state.formsDisabled}
              v-model={item.packQuantity}
              type="number"
              placeholder={`请输入${state.packUnitObjList[index].label}`}
              clearable
              maxlength="8"
            />
          </tz-cell>
          <tz-cell title={state.packUnitObjList[index].title} border required>
            <tz-search-picker
              disabled={state.formsDisabled}
              v-model={item.packUnit}
              range={state.packUnitObjList[index].dicMap}
              searchPlaceholder="请输入单位查询"
              rangeKey="nameLabel"
              valueKey="code"
            ></tz-search-picker>
          </tz-cell>
          {!hidePermitList(item) && (
            <tz-cell
              class="arrow-cell"
              title="许可证信息"
              border
              onClick={() =>
                navigateTo({
                  path: "/pages/subHK/ccrn/licence/index",
                  query: {
                    goodsIndex: index,
                    formsDisabled: state.formsDisabled,
                    permitsList:
                      item.permitsList && item.permitsList.length
                        ? JSON.stringify(item.permitsList)
                        : undefined,
                  },
                })
              }
            >
              <tz-text>
                {item.permitsList && item.permitsList.length ? "已填写" : ""}
              </tz-text>
              <tz-icon class="tz-input-icon" name="arrow-right"></tz-icon>
            </tz-cell>
          )}
        </tz-form>
      ))}
    </tz-view>
  );
};
